package com.example.core;

import com.example.core.event.AsyncEvent;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class EventBusListener implements InitializingBean, DisposableBean {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private EventBus eventBus;

    @Override
    public void afterPropertiesSet() throws Exception {
        this.eventBus.register(this);
    }

    @Override
    public void destroy() throws Exception {
        this.eventBus.unregister(this);
    }

    @Subscribe
    public void handleEvent(AsyncEvent asyncEvent) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (asyncEvent != null){
            asyncEvent.getHandler().handler(asyncEvent.getObject());
        }
    }
}
